package service

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
)

type ProJson struct {
	ID            int                   `json:"id"`
	Name          string                `json:"name"`          //商品名称
	SubName       string                `json:"sub_name"`      //商品副名称
	Pic           string                `json:"pic"`           //商品主图
	Pics          string                `json:"pics"`          //商品图片
	Sales         int                   `json:"sales"`         //已售数量
	Detail        string                `json:"detail"`        //商品详情
	MarketPrice   decimal.Decimal       `json:"market_price"`  //市场价
	SellPrice     decimal.Decimal       `json:"sell_price"`    //销售价
	Scoredkmaxset int                   `json:"scoredkmaxset"` //积分抵扣设置 0按照系统设置抵扣 1单独设置抵扣比例 2单独设置抵扣金额 -1不可用积分抵扣
	Scoredkmaxval decimal.Decimal       `json:"scoredkmaxval"` //积分抵扣时最多抵扣多少
	Type          int                   `json:"type"`
	Tag           string                `json:"tag"`
	Guige         string                `json:"guige"`
	TjShop        []models.MShopProduct `json:"tj_shop"`
	TjFu          []models.MFuProduct   `json:"tj_fu"`
	GuiGeList     []GuiGeData           `json:"gui_ge_list"`
	Region        []models.MRegion      `json:"region"`
}
type GuiGeData struct {
	ID          int             `json:"id"`
	Proid       int             `json:"proid"`        //商品ID
	Name        string          `json:"name"`         //规格名称
	Pic         string          `json:"pic"`          //规格图片
	MarketPrice decimal.Decimal `json:"market_price"` //市场价
	SellPrice   decimal.Decimal `json:"sell_price"`   //销售价
	Weight      int             `json:"weight"`       //重量
	Stock       int             `json:"stock"`        //库存
	Sales       int             `json:"sales"`        //已售数量
	Ks          string          `json:"ks"`           //规格结构
	Barcode     string          `json:"barcode"`      //规格条形码编号
}

// 获取商品详情页
func GetShopProductInfo(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var proData models.MShopProduct
	err = models.DB.Model(new(models.MShopProduct)).Where("id=? AND aid=?", jsonData.Id, jsonData.Aid).First(&proData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var proJS ProJson
	proJS.Pic = proData.Pic
	proJS.Name = proData.Name
	proJS.SubName = proData.SubName
	proJS.ID = proData.ID
	proJS.SellPrice = proData.SellPrice
	proJS.MarketPrice = proData.MarketPrice
	proJS.Sales = proData.Sales
	proJS.Detail = proData.Detail
	proJS.Pics = proData.Pics
	proJS.Guige = proData.Guigedata
	proJS.Tag = proData.Tag
	proJS.Type = proData.Type
	proJS.Scoredkmaxset = proData.Scoredkmaxset
	proJS.Scoredkmaxval = proData.Scoredkmaxval
	//获取用户服务区域/或者配上区域
	if proData.Type == 1 {
		newArr := strings.Split(proData.Freightdata, ",")
		for _, v := range newArr {
			var regionData models.MRegion
			num, _ := strconv.Atoi(v)
			err = models.DB.Model(new(models.MRegion)).Where("id=?", num).First(&regionData).Error
			if err != nil {
				define.Response.ResultFail(c, 10005, define.JsonDataX, "")
				return
			}
			proJS.Region = append(proJS.Region, regionData)
		}

	}
	//获取规格
	var GuigeData []models.MShopGuige
	err = models.DB.Model(new(models.MShopGuige)).Where("proid=?", jsonData.Id).Find(&GuigeData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	for _, v := range GuigeData {
		one := GuiGeData{
			ID:          v.ID,
			Proid:       v.Proid,
			Name:        v.Name,
			Pic:         v.Pic,
			MarketPrice: v.MarketPrice,
			SellPrice:   v.SellPrice,
			Weight:      v.Weight,
			Stock:       v.Stock,
			Sales:       v.Sales,
			Ks:          v.Ks,
			Barcode:     v.Barcode,
		}
		proJS.GuiGeList = append(proJS.GuiGeList, one)
	}
	//判断商品是否有推荐商品
	if proData.TjProid != "" {
		//有推荐商品
		var proIds = strings.Split(proData.TjProid, ",")
		for _, v := range proIds {
			num, _ := strconv.Atoi(v)
			var proOne models.MShopProduct
			err = models.DB.Model(new(models.MShopProduct)).Where("id=?", num).First(&proOne).Error
			if err != nil {
				define.Response.ResultFail(c, 10003, define.JsonDataX, "")
				return
			}
			proJS.TjShop = append(proJS.TjShop, proOne)
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    proJS,
	})
}

// 获取二级分类与商品列表
type returnShopCate struct {
	CateName string        `json:"cate_name"`
	ID       int           `json:"id"`
	Pid      int           `json:"pid"`
	SubName  string        `json:"sub_name"`
	Pic      string        `json:"pic"`
	Type     int           `json:"type"`
	ShopList []ProductJson `json:"shop_list"`
}

func GetShopCateList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []models.MShopCategory
	tx := models.DB.Model(new(models.MShopCategory)).Where("aid=? AND status=?", jsonData.Aid, 1)
	if jsonData.Id > 0 {
		tx = tx.Where("id=?", jsonData.Id)
	}
	if jsonData.Pid > 0 {
		tx = tx.Where("pid=?", jsonData.Pid)
	}
	if jsonData.Name != "" {
		tx = tx.Where("name LIKE ?", "%"+jsonData.Name+"%")
	}
	tx = tx.Order("sort desc,id").Find(&list)
	if tx.Error != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var listData []returnShopCate
	//循环获取每个栏目下的商品
	for _, v := range list {
		var proList []ProductJson
		if v.Type == 2 {
			selectData := "m_shop_product.id,m_shop_product.name,m_shop_product.pic,m_shop_product.sub_name,m_shop_product.sales,m_shop_product.market_price,m_shop_product.sell_price,m_shop_product.type"
			txP := models.DB.Table("m_shop_product").Select(selectData).Where("status = ?", 1)
			txP = txP.Where("cate_id=? or cate_id2=? or cate_id3=? or cate_id4=? or cate_id5=? or cate_id6=?", v.ID, v.ID, v.ID, v.ID, v.ID, v.ID).Find(&proList)
			if err != nil {
				define.Response.ResultFail(c, 10001, define.JsonDataX, "")
				return
			}
		} else if v.Type == 1 {
			selectData := "m_fu_product.id,m_fu_product.name,m_fu_product.pic,m_fu_product.sub_name,m_fu_product.sales,m_fu_product.market_price,m_fu_product.sell_price,m_fu_product.type"
			txP := models.DB.Table("m_fu_product").Select(selectData).Where("status = ?", 1)
			txP = txP.Where("cate_id=? or cate_id2=? or cate_id3=? or cate_id4=? or cate_id5=? or cate_id6=?", v.ID, v.ID, v.ID, v.ID, v.ID, v.ID).Find(&proList)
			if err != nil {
				define.Response.ResultFail(c, 10001, define.JsonDataX, "")
				return
			}
		}
		one := returnShopCate{
			CateName: v.Name,
			SubName:  v.SubName,
			ID:       v.ID,
			Pic:      v.Pic,
			Pid:      v.Pid,
			Type:     v.Type,
			ShopList: proList,
		}
		listData = append(listData, one)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    listData,
	})
}

// 获取商品列表
func GetShopList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	tx := models.DB
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	if jsonData.Type == 1 {
		var list []models.MFuProduct
		tx = tx.Model(new(models.MFuProduct)).Where("aid=? AND status=?", jsonData.Aid, 1)
		if jsonData.Name != "" {
			tx = tx.Where("name LIKE ? or sub_name  LIKE ?", "%"+jsonData.Name+"%", "%"+jsonData.Name+"%")
		}
		if jsonData.Id > 0 {
			tx = tx.Where("id=?", jsonData.Id)
		}
		if jsonData.Pid > 0 {
			tx = tx.Where("gid=? or gid1=? or gid2=? or gid3=? or gid4=? or gid5=? or gid6=?", jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid)
		}
		if jsonData.Mid > 0 {
			tx = tx.Where("cate_id=? or cate_id2=? or cate_id3=? or cate_id4=? or cate_id5=? or cate_id6=?", jsonData.Mid, jsonData.Mid, jsonData.Mid, jsonData.Mid, jsonData.Mid, jsonData.Mid)
		}
		tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("sort desc,id").Find(&list)
		if tx.Error != nil {
			define.Response.ResultFail(c, 10001, define.JsonDataX, "")
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"success": true,
			"code":    0,
			"data": map[string]interface{}{
				"list":  list,
				"count": count,
			},
		})
	} else {
		var list []models.MShopProduct
		tx = tx.Model(new(models.MShopProduct)).Where("aid=? AND status=?", jsonData.Aid, 1)
		if jsonData.Name != "" {
			tx = tx.Where("name LIKE ? or sub_name  LIKE ?", "%"+jsonData.Name+"%", "%"+jsonData.Name+"%")
		}
		if jsonData.Id > 0 {
			tx = tx.Where("id=?", jsonData.Id)
		}
		if jsonData.Pid > 0 {
			tx = tx.Where("gid=? or gid1=? or gid2=? or gid3=? or gid4=? or gid5=? or gid6=?", jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid)
		}
		if jsonData.Mid > 0 {
			tx = tx.Where("cate_id=? or cate_id2=? or cate_id3=? or cate_id4=? or cate_id5=? or cate_id6=?", jsonData.Mid, jsonData.Mid, jsonData.Mid, jsonData.Mid, jsonData.Mid, jsonData.Mid)
		}
		tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("sort desc,id").Find(&list)
		if tx.Error != nil {
			define.Response.ResultFail(c, 10001, define.JsonDataX, "")
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"success": true,
			"code":    0,
			"data": map[string]interface{}{
				"list":  list,
				"count": count,
			},
		})
	}
}

// 获取分组商品及信息
type ProGroup struct {
	ID      int           `json:"id"`
	Name    string        `json:"name"`     //名称
	Pic     string        `json:"pic"`      //图片
	SubName string        `json:"sub_name"` //副标题
	Banner  string        `json:"banner"`
	IsRow   int           `json:"is_row"`
	Type    int           `json:"type"`
	Pro     []ProductJson `json:"pro"`
}
type ProductJson struct {
	ID            int     `json:"id"`            //id
	Type          int     `json:"type"`          //
	Bid           int     `json:"bid"`           //商户ID
	Name          string  `json:"name"`          //商品名称
	Pic           string  `json:"pic"`           //商品主图
	Sales         int     `json:"sales"`         //已售数量
	MarketPrice   float64 `json:"market_price"`  //市场价
	SellPrice     float64 `json:"sell_price"`    //销售价
	Scoredkmaxset int     `json:"scoredkmaxset"` //积分抵扣设置 0按照系统设置抵扣 1单独设置抵扣比例 2单独设置抵扣金额 -1不可用积分抵扣
	SubName       string  `json:"sub_name"`
}

func GetGroupInfo(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//获取所以分组
	var group []models.MShopGroup
	tx := models.DB.Model(new(models.MShopGroup)).Where("aid=? AND status=?", jsonData.Aid, jsonData.Status)
	if jsonData.Id > 0 {
		tx = tx.Where("id=?", jsonData.Id)
	}
	if jsonData.Type > 0 {
		tx = tx.Where("from_id=?", jsonData.Type)
	}
	tx = tx.Order("sort desc,id").Find(&group)
	if tx.Error != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var list []ProGroup
	//循环分组获取产品信息
	for _, v := range group {
		var proList []ProductJson
		if v.Type == 2 {
			selectData := "m_shop_product.id,m_shop_product.name,m_shop_product.pic,m_shop_product.sub_name,m_shop_product.sales,m_shop_product.market_price,m_shop_product.sell_price,m_shop_product.type"
			txP := models.DB.Table("m_shop_product").Select(selectData).Where("status = ?", 1)
			txP = txP.Where("gid=? or gid1=? or gid2=? or gid3=? or gid4=? or gid5=? or gid6=?", jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id)
			txP = txP.Limit(jsonData.Limit).Find(&proList)
			if err != nil {
				define.Response.ResultFail(c, 10001, define.JsonDataX, "")
				return
			}
		} else {
			selectData := "m_fu_product.id,m_fu_product.name,m_fu_product.pic,m_fu_product.sub_name,m_fu_product.sales,m_fu_product.market_price,m_fu_product.sell_price,m_fu_product.type"
			txP := models.DB.Table("m_fu_product").Select(selectData).Where("status = ?", 1)
			txP = txP.Where("gid=? or gid1=? or gid2=? or gid3=? or gid4=? or gid5=? or gid6=?", jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id, jsonData.Id)
			txP = txP.Limit(jsonData.Limit).Find(&proList)
			if err != nil {
				define.Response.ResultFail(c, 10001, define.JsonDataX, "")
				return
			}
		}

		one := ProGroup{
			ID:      v.ID,
			Name:    v.Name,
			Pic:     v.Pic,
			SubName: v.SubName,
			IsRow:   v.IsRow,
			Type:    v.Type,
			Banner:  v.Banner,
			Pro:     proList,
		}
		list = append(list, one)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    list,
	})
}

// 获取分组
func GetShopGroupList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MShopGroup
	var count int64
	tx := models.DB.Model(new(models.MShopGroup)).Where("aid=? AND status=?", jsonData.Aid, jsonData.Status)
	if jsonData.Id > 0 {
		tx = tx.Where("id=?", jsonData.Id)
	}
	if jsonData.Pid > -1 {
		tx = tx.Where("from_id=?", jsonData.Pid)
	}
	tx = tx.Count(&count).Find(&list)
	if tx.Error != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 获取栏目下的商品
func GetFuShopList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MFuProduct
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MFuProduct)).Where("aid=? AND status = ?", jsonData.Aid, 1)
	if jsonData.Pid > 0 {
		tx = tx.Where("cate_id=? or cate_id2=? or cate_id3=? or cate_id4=? or cate_id5=? or cate_id6=?", jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("sort desc,id").Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 获取分组下的商品
func GetFuGroupList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MFuProduct
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MFuProduct)).Where("aid=? AND status = ?", jsonData.Aid, 1)
	if jsonData.Pid > 0 {
		tx = tx.Where("gid=? or gid1=? or gid2=? or gid3=? or gid4=? or gid5=? or gid6=?", jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid, jsonData.Pid)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("sort desc,id").Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}
